<template>
  <div class="app-container">
	  <div>
	  	  <el-date-picker
	  		v-model="month"
	  		type="month"
			value-format="yyyy-M"
			@change="monthChoose"
	  		placeholder="选择查询月份">
	  	  </el-date-picker>
	  </div>
	  <el-divider></el-divider>     
	  <el-calendar v-model="calendarMonth"> 
	    <template #dateCell="{date, data}">
	      <div class="">
	        <div class="text">{{formatDate(date)}}</div>
	        <div class="schedule">
	          <span v-if='nowTime.getTime() - date.getTime() > 86400000' style="pointer-events: initial;">
					<el-tag type="info" @click="look(data)" v-if='getSchedule(date)'>查看记录</el-tag>
					<el-tag type="warning" v-else>未设置</el-tag>
			  </span>
			  <div v-else>
				  <div v-if='getSchedule(date)'>
					  <el-tag type="success">已设置</el-tag>
					  <div style="margin-top: 10px;">
						  <el-tag type="info" @click="look(date)">查看记录</el-tag>
					  </div>
				  </div>
				  <span v-else><el-tag @click="setFood(date)">待设置</el-tag></span>
			  </div>
	        </div>
	      </div>
	    </template>
	  </el-calendar>
	  
	  <!-- 添加或修改岗位对话框 -->
	  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
	    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
			<el-form-item label="餐食日期" prop="caterDate" required>
			  <el-date-picker
					v-model="form.caterDate"
					type="date"
					value-format="yyyy-MM-dd"
					@change="monthChoose"
					placeholder="选择查询月份">
			  </el-date-picker>
			</el-form-item>
		  <h3>早餐</h3>
		  <el-form-item label="图片">
		  	<div @click="fileTypeChoose('breakfristFileList')">
		  		<el-upload
		  		  multiple
		  		  :action="uploadFileUrl"
		  		  :before-upload="handleBeforeUpload"
		  		  :file-list="breakfristFileList"
		  		  :limit="5"
		  		  :on-error="handleUploadError"
		  		  :on-exceed="handleExceed"
		  		  :on-success="handleUploadSuccess"
		  		  :show-file-list="true"
		  		  :headers="headers"
		  		  list-type="picture-card"
		  		  :on-remove="handleDelete"
		  		  class="upload-file-uploader"
		  		  ref="fileUpload"
		  		>
		  		  <i class="el-icon-plus"></i>
		  		</el-upload>
		  	</div>
		  </el-form-item>
	      <el-form-item label="早餐价格" prop="breakfastPrice">
	  		<el-input placeholder="请输入早餐价格" type='number' v-model="form.breakfastPrice">
	  		   <template slot="append">元</template>
	  		</el-input>
	      </el-form-item>
		  <el-form-item label="介绍" prop="breakfastIntroduce">
			  <el-input v-model="form.breakfastIntroduce" placeholder="请输入介绍" type="textarea" />
		  </el-form-item>
		  <h3>午餐</h3>
		  <el-form-item label="图片">
		  	<div @click="fileTypeChoose('lunchFileList')">
				<el-upload
				  multiple
				  :action="uploadFileUrl"
				  :before-upload="handleBeforeUpload"
				  :file-list="lunchFileList"
				  :limit="5"
				  :on-error="handleUploadError"
				  :on-exceed="handleExceed"
				  :on-success="handleUploadSuccess"
				  :show-file-list="true"
				  :headers="headers"
				  list-type="picture-card"
				  :on-remove="handleDelete"
				  class="upload-file-uploader"
				  ref="fileUpload"
				>
				  <i class="el-icon-plus"></i>
				</el-upload>
			</div>
		  </el-form-item>
		  <el-form-item label="午餐价格" prop="lunchPrice">
				<el-input placeholder="请输入午餐价格" type='number' v-model="form.lunchPrice">
				   <template slot="append">元</template>
				</el-input>
		  </el-form-item>
		  <el-form-item label="介绍" prop="lunchIntroduce">
			  <el-input v-model="form.lunchIntroduce" placeholder="请输入介绍" type="textarea" />
		  </el-form-item>
		  <h3>晚餐</h3>
		  <el-form-item label="图片">
		  	<div @click="fileTypeChoose('dinnerFileList')">
		  		<el-upload
		  		  multiple
		  		  :action="uploadFileUrl"
		  		  :before-upload="handleBeforeUpload"
		  		  :file-list="dinnerFileList"
		  		  :limit="5"
		  		  :on-error="handleUploadError"
		  		  :on-exceed="handleExceed"
		  		  :on-success="handleUploadSuccess"
		  		  :show-file-list="true"
		  		  :headers="headers"
		  		  list-type="picture-card"
		  		  :on-remove="handleDelete"
		  		  class="upload-file-uploader"
		  		  ref="fileUpload"
		  		>
		  		  <i class="el-icon-plus"></i>
		  		</el-upload>
		  	</div>
		  </el-form-item>
		  <el-form-item label="晚餐价格" prop="dinnerPrice">
			<el-input placeholder="请输入晚餐价格" type='number' v-model="form.dinnerPrice">
			   <template slot="append">元</template>
			</el-input>
		  </el-form-item>
		  <el-form-item label="介绍" prop="dinnerIntroduce">
			  <el-input v-model="form.dinnerIntroduce" placeholder="请输入介绍" type="textarea" />
		  </el-form-item>
	    </el-form>
	    <div slot="footer" class="dialog-footer">
	      <el-button type="primary" @click="submitForm">确 定</el-button>
	      <el-button @click="cancel">取 消</el-button>
	    </div>
	  </el-dialog>
  </div>
</template>
 
<script>
import {
	listDailyCatering,
	insertDailyCatering,
	editDailyCatering,
	dateDetail,
	allListDailyCatering
} from "@/api/food/dayfood";
import FileUpload from '@/components/FileUpload'
import { strchangeArr,strchangeArrName } from "@/utils/index";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
	  month:'',
	  nowTime: new Date(),
	  calendarMonth: new Date(),
      schedules: [],
	  number: 0,
	  uploadList: [],
	  baseUrl: process.env.VUE_APP_BASE_API,
	  uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
	  headers: {
	    Authorization: "Bearer " + getToken(),
	  },
	  fileSize:3,
	  fileType:['png', 'jpg', 'jpeg'],
	  open:false,
	  // 表单参数
	  form: {},
	  //上传图片
	  fileList:[],
	  // 遮罩层
	  loading: true,
	  //上传早餐图片
	  breakfristFileList:[],
	  //上传午餐图片
	  lunchFileList:[],
	  //上传晚餐图片
	  dinnerFileList:[],
	  title:'三餐设置',
	  filedType:null,
	  // 表单校验
	  rules: {
	    breakfastPrice: [
	      { required: true, message: "早餐价格不能为空", trigger: "blur" }
	    ],
		breakfastIntroduce: [
		  { required: true, message: "早餐介绍不能为空", trigger: "blur" }
		],
		lunchPrice: [
		  { required: true, message: "午餐名称不能为空", trigger: "blur" }
		],
		lunchIntroduce: [
		  { required: true, message: "午餐介绍不能为空", trigger: "blur" }
		],
		dinnerPrice: [
		  { required: true, message: "晚餐不能为空", trigger: "blur" }
		],
		dinnerIntroduce: [
		  { required: true, message: "晚餐介绍不能为空", trigger: "blur" }
		],
		caterDate: [
		  { required: true, message: "餐饮日期不能为空", trigger: "change" }
		],
	  }
    };
  },
  created() {
	  this.getList()
  },
  methods: {
	  // 上传前校检格式和大小
	  handleBeforeUpload(file) {
	    // 校检文件类型
	    if (this.fileType) {
	      const fileName = file.name.split('.');
	      const fileExt = fileName[fileName.length - 1];
	      const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
	      if (!isTypeOk) {
	        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
	        return false;
	      }
	    }
	    // 校检文件大小
	    if (this.fileSize) {
	      const isLt = file.size / 1024 / 1024 < this.fileSize;
	      if (!isLt) {
	        this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
	        return false;
	      }
	    }
	    this.$modal.loading("正在上传文件，请稍候...");
	    this.number++;
	    return true;
	  },
	  // 文件个数超出
	  handleExceed() {
	    this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
	  },
	  // 上传失败
	  handleUploadError(err) {
	    this.$modal.msgError("上传文件失败，请重试");
	    this.$modal.closeLoading();
	  },
	  // 上传成功回调
	  handleUploadSuccess(res, file) {
	    if (res.code === 200) {
	      this.uploadList.push({ name: res.fileName, url: res.url });
	      this.uploadedSuccessfully();
	    } else {
	      this.number--;
	      this.$modal.closeLoading();
	      this.$modal.msgError(res.msg);
	      this.$refs.fileUpload.handleDelete(file);
	      this.uploadedSuccessfully();
	    }
	  },
	  // 删除文件
	  handleDelete(index) {
	    this[this.filedType].splice(index, 1);
	  },
	  // 上传结束处理
	  uploadedSuccessfully() {
	    if (this.number > 0 && this.uploadList.length === this.number) {
	      this[this.filedType] = this[this.filedType].concat(this.uploadList);
	      this.uploadList = [];
	      this.number = 0;
	      this.$modal.closeLoading();
	    }
	  },
	  // 获取文件名称
	  getFileName(name) {
	    // 如果是url那么取最后的名字 如果不是直接返回
	    if (name.lastIndexOf("/") > -1) {
	      return name.slice(name.lastIndexOf("/") + 1);
	    } else {
	      return name;
	    }
	  },
	  // 对象转成指定字符串分隔
	  listToString(list, separator) {
	    let strs = "";
	    separator = separator || ",";
	    for (let i in list) {
	      strs += list[i].url + separator;
	    }
	    return strs != '' ? strs.substr(0, strs.length - 1) : '';
	  },
	  // 取消按钮
	  cancel() {
	    this.open = false;
	    this.reset();
	  },
	  // 表单重置
	  reset() {
	    this.dinnerFileList = []
	    this.breakfristFileList = []
	    this.lunchFileList = []
	    this.form = {}
	    this.resetForm("form");
	  },
	  //图片类型选择
	  fileTypeChoose(res){
		  this.filedType = res
	  },
	  /** 查询列表 */
	  getList() {
	    this.loading = true;
	    allListDailyCatering().then(response => {
	      this.schedules = response.data.map(i=>{
			  i.date = i.caterDate
			  return i
		  })
	      this.total = response.total;
	      this.loading = false;
	    });
	  },
    getSchedule(date) {
      return this.schedules.find(schedule => schedule.date === this.formatDate(date));
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1 < 10 ? '0'+parseInt(date.getMonth() + 1) : parseInt(date.getMonth() + 1);
      const day = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
      return `${year}-${month.toString()}-${day.toString()}`;
    },
	monthChoose(res){
		let data = res.split('-')
		this.calendarMonth = new Date(data[0], parseInt(data[1]-1), 1)
	},
	look(res){
		let day = !res.day ? res : res.day
		let data = {
			caterDate:day
		}
		dateDetail(data).then(response => {
		  this.form = response.data
		  this.breakfristFileList = strchangeArrName(this.form.breakfastImage)
		  this.dinnerFileList =  strchangeArrName(this.form.dinnerImage)
		  this.lunchFileList = strchangeArrName(this.form.lunchImage)
		  this.open = true 
		}); 
	},
	/** 提交按钮 */
	submitForm: function() {
	  this.form.breakfastImage = this.listToString(this.breakfristFileList)
	  this.form.dinnerImage = this.listToString(this.dinnerFileList)
	  this.form.lunchImage = this.listToString(this.lunchFileList)
	  this.$refs["form"].validate(valid => {
	    if (valid) {
	      if (this.form.id != undefined) {
	        editDailyCatering(this.form).then(response => {
	          this.$modal.msgSuccess("修改成功");
	          this.open = false;
	          this.getList();
	        });
	      } else {
	        insertDailyCatering(this.form).then(response => {
	          this.$modal.msgSuccess("新增成功");
	          this.open = false;
	          this.getList();
	        });
	      }
	    }
	  });
	},
	//设置餐食
	setFood(date){
		this.reset()
		this.form.caterDate = this.formatDate(date)
		this.open = true
	}
  }
};
</script>
 
<style scoped>
.date-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.text {
  margin-right: 10px;
}
.schedule {
  text-align: center;
  color: #666;
  padding-top: 20px;
}
</style>